package euler.p051_100;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import euler.MainEuler;
import euler.helper.NaturalHelper;
import euler.helper.Utils;

public class Euler051 extends MainEuler {

	/*
	 * By replacing the 1st digit of *3, it turns out that six of the nine
	 * possible values: 13, 23, 43, 53, 73, and 83, are all prime.
	 *
	 * By replacing the 3rd and 4th digits of 56**3 with the same digit, this
	 * 5-digit number is the first example having seven primes among the ten
	 * generated numbers, yielding the family: 56003, 56113, 56333, 56443,
	 * 56663, 56773, and 56993. Consequently 56003, being the first member of
	 * this family, is the smallest prime with this property.
	 *
	 * Find the smallest prime which, by replacing part of the number (not
	 * necessarily adjacent digits) with the same digit, is part of an eight
	 * prime value family.
	 */
	public String resolve(int tamañoFamilia) {

		for (int n = 56005; 0 < n && n <= Integer.MAX_VALUE; n+=2) {
			if (primeHelper.isPrime(n)) {
				int[] digitos = NaturalHelper.digitos(n, 10, false);
				// you only need to try replacing the digits '0', '1', and '2'.
				for (int i = 0; i < 4; i++) {
					if (Utils.contains(digitos, i)) {
						Set<Integer> primos = new HashSet<Integer>();
						primos.add(n);

						for (int j = 0; j < 10; j++) {
							if (j != i) {
								int[] digitos2 = Arrays.copyOf(digitos, digitos.length);

								Utils.reemplazar(digitos2,i,j);

								int m = (int)NaturalHelper.toNumber(digitos2,10);
								if (m > n && !primos.contains(m) && primeHelper.isPrime(m)) {
									primos.add(m);
								}
							}
						}

						if (primos.size() >= tamañoFamilia) {
							return String.valueOf(n);
						}
					}
				}
			}
		}

		return null;
	}

}
